import { useUserStore } from '@/stores/user'

/**
 * 检查用户是否有指定角色
 * @param {string|Array} roles - 角色或角色数组
 * @returns {boolean}
 */
export function hasRole(roles) {
  const userStore = useUserStore()
  const userRoles = userStore.roles

  if (typeof roles === 'string') {
    return userRoles.includes(roles)
  }

  if (Array.isArray(roles)) {
    return roles.some(role => userRoles.includes(role))
  }

  return false
}

/**
 * 检查用户是否有指定权限
 * @param {string|Array} permissions - 权限或权限数组
 * @returns {boolean}
 */
export function hasPermission(permissions) {
  const userStore = useUserStore()
  const userPermissions = userStore.permissions

  // 超级管理员拥有所有权限
  if (userPermissions.includes('*:*:*')) {
    return true
  }

  if (typeof permissions === 'string') {
    return userPermissions.includes(permissions)
  }

  if (Array.isArray(permissions)) {
    return permissions.some(permission => userPermissions.includes(permission))
  }

  return false
}

/**
 * 检查用户是否有访问路由的权限
 * @param {Object} route - 路由对象
 * @returns {boolean}
 */
export function hasRoutePermission(route) {
  if (!route.meta || !route.meta.roles) {
    return true
  }

  return hasRole(route.meta.roles)
}

/**
 * 过滤用户有权限的路由
 * @param {Array} routes - 路由数组
 * @returns {Array}
 */
export function filterRoutes(routes) {
  const result = []

  routes.forEach(route => {
    if (hasRoutePermission(route)) {
      const newRoute = { ...route }
      if (newRoute.children) {
        newRoute.children = filterRoutes(newRoute.children)
      }
      result.push(newRoute)
    }
  })

  return result
}

/**
 * 检查是否为超级管理员
 * @returns {boolean}
 */
export function isSuperAdmin() {
  return hasRole('admin') || hasPermission('*:*:*')
}
